//
//  Fraction.m
//  OC03_属性
//
//  Created by dllo on 15/12/2.
//  Copyright © 2015年 dllo. All rights reserved.
//

#import "Fraction.h"

@implementation Fraction

- (instancetype)initWithNumerator:(NSInteger)numerator
                      denominator:(NSInteger)denominator {
    self = [super init];
    if (self) {
        self.numerator = numerator;
        self.denominator = denominator;
    }
    return self;
}


+ (instancetype)fractionWithNumerator:(NSInteger)numerator
                          denominator:(NSInteger)denominator {
    Fraction *fraction = [[Fraction alloc] initWithNumerator:numerator denominator:denominator];
    return fraction;
}


/** 加法 */
- (Fraction *)addOperationWithFraction:(Fraction *)fraction {
    Fraction *newFra = [[Fraction alloc] init];
    newFra.numerator = self.numerator * fraction.denominator + fraction.numerator * self.denominator;
    newFra.denominator = self.denominator * fraction.denominator;
    [newFra reduce];
    return newFra;
}

/** 减法 */
- (Fraction *)subtractionOperationWithFraction:(Fraction *)fraction {
    Fraction *newFra1 = [[Fraction alloc] init];
    newFra1.numerator = self.numerator * fraction.denominator - fraction.numerator * self.denominator;
    newFra1.denominator = self.denominator * fraction.denominator;
    [newFra1 reduce];
    return newFra1;
}

/** 乘法 */
- (Fraction *)multiplicationOperationWithFraction:(Fraction *)fraction {
    Fraction *newFra2 = [[Fraction alloc] init];
    newFra2.numerator = self.numerator * fraction.numerator;
    newFra2.denominator = self.denominator * fraction.denominator;
    [newFra2 reduce];
    return newFra2;
}

/** 除法 */
- (Fraction *)divisionOperationWithFraction:(Fraction *)fraction {
    Fraction *newFra3 = [[Fraction alloc] init];
    newFra3.numerator = self.numerator * fraction.denominator;
    newFra3.denominator = self.denominator * fraction.numerator;
    [newFra3 reduce];
    return newFra3;
}

/** 约分 */

- (void)reduce {
    
    /** 最大公约数 */
    long m = self.numerator;
    long n = self.denominator;
    long temp;
    while (m % n !=0) {
        temp = m % n;
        m = n;
        n = temp;    // n为最大公约数
    }
    self.numerator /= n;
    self.denominator /= n;
}


/** 返回值类型:NSComparisonResult 是个枚举值, 在OC比较方法中, 经常用到的类型. 里面有3个值: -1, 0, 1. 其中 -1 (NSOrderedAscending)表示升序,即前面的数小. 0(NSOrderedSame)表示相等. 1(NSOrderedDescending)表示降序, 即前一个数大 */
- (NSComparisonResult)compareWithFraction:(Fraction *)frac {
    
    Fraction *newFraction = [self subtractionOperationWithFraction:frac];   /**< 两个分数的差 */
    
    /** 判断两个分数的差是正数还是负数 */
    if (newFraction.numerator * newFraction.denominator > 0) {
        return NSOrderedDescending;
    } else if (newFraction.numerator * newFraction.denominator <0){
        return NSOrderedAscending;
    } else {
        return NSOrderedSame;
    }
    
}










@end
